package com.itqf.service.impl;

import com.itqf.dao.CarDao;
import com.itqf.dao.GoodsDao;
import com.itqf.dao.impl.CarDaoImpl;
import com.itqf.dao.impl.GoodsDaoImpl;
import com.itqf.entity.Car;
import com.itqf.entity.Goods;
import com.itqf.service.CarService;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

public class CarServiceImpl implements CarService {
    @Override
    public void createCar(int userno, String gid) throws SQLException, InvocationTargetException, IllegalAccessException {
        CarDao carDao = new CarDaoImpl();
        Car car = carDao.hasCar(userno,gid);
        if(car!=null){
            car.setNumber(car.getNumber()+1);
            carDao.updateCar(car);
        }else{
            GoodsDao goodsDao = new GoodsDaoImpl();
            Goods goods = goodsDao.selectGoodsByGid(Integer.parseInt(gid));
            car = new Car();
            car.setNumber(1);
            car.setGid(Integer.parseInt(gid));
            car.setGoods(goods);
            car.setUserno(userno);
            carDao.insertCar(car);
        }
    }

    @Override
    public List<Car> findAll(int userno) throws IllegalAccessException, SQLException, InvocationTargetException {
        CarDao carDao = new CarDaoImpl();
        List<Car> list =  carDao.selectCarsByUserno(userno);
        return list;
    }

    @Override
    public void deleteCarByCid(String cid) throws SQLException {
        CarDao carDao = new CarDaoImpl();
        carDao.deleteCarByCid(cid);
    }

    @Override
    public void updateCarByCid(String cid, String gprice, String number) throws SQLException {
        BigDecimal num = new BigDecimal(number);
        BigDecimal price = new BigDecimal(gprice);
        BigDecimal count = price.multiply(num);
        CarDao carDao = new CarDaoImpl();
        carDao.updateByCid(count,number,cid);
    }

    @Override
    public void clearCar(String userno) throws SQLException {
        CarDao carDao = new CarDaoImpl();
        carDao.clearCarByUserno(userno);
    }
}
